package org.base.dao.config;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;

@Configuration
public class MybatisConfig {
	
	private static final Logger log = LoggerFactory.getLogger(MybatisConfig.class);
	
	/**
	 * 配置事务管理
	 * 
	 */
	@Bean
	public DataSourceTransactionManager transactionManager(@Qualifier("dataSource")DataSource dataSource) {
		log.info("init basisTransactionManager");
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean
	public SqlSessionFactory sqlSessionFactory(GlobalConfiguration globalConfig,@Qualifier("dataSource")DataSource dataSource,
			@Value("${mybatis-plus.mapper-locations}") String mapperLocations,
			@Value("${mybatis-plus.config-location}") String configLocation,
			@Value("${mybatis-plus.type-aliases-package}") String typeAliasesPackage
			) throws Exception {
		log.info("init SqlSessionFactory");
		MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
		// 数据源
		sqlSessionFactory.setDataSource(dataSource);
		// 全局配置
		sqlSessionFactory.setGlobalConfig(globalConfig);
		Interceptor[] interceptor = {new PaginationInterceptor()};
		// 分页插件
		sqlSessionFactory.setPlugins(interceptor);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			// 自动扫描Mapping.xml文件
			sqlSessionFactory.setMapperLocations(resolver.getResources(mapperLocations));
			sqlSessionFactory.setConfigLocation(resolver.getResource(configLocation));
			sqlSessionFactory.setTypeAliasesPackage(typeAliasesPackage);
			return sqlSessionFactory.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}

}
